import {
	defineStore
} from "pinia";

import cookie from "@/utils/cookie";
import {
	navigateTo
} from "@/utils/router";

export const useMainStore = defineStore("main", {
	state: () => ({
		store: {},
		cart: [],
		orderType: "takein",
		address: {},
		addresses: {},
		member: {},
		accesses: [],
		openid: "",
		token: "",
		lang: "zh-cn",
		cookieKey: "YSESSID=yshop-e4dk4o2utr3c0n95tp42p745ai",
		// 默认地为你为北京地址
		location: {},
		mycoupon: {},
		buyerId: "", // 添加支付宝用户ID
	}),
	getters: {
		isLogin(state) {
			if (state.accesses.length > 0) {
				return true;
			}
			//是否登录
			return Object.keys(state.member).length > 0;
		},
		//isLogin: state => Object.keys(state.member).length > 0	//是否登录
	},
	actions: {
		SET_COUPON(coupon) {
			this.mycoupon = coupon;
		},
		SET_ORDER_TYPE(type) {
			this.orderType = type;
			uni.setStorage({
				key: "orderType",
				data: type,
			});
		},
		SET_MEMBER(member) {
			this.member = member;
			cookie.set("userinfo", member);
		},
		SET_ACCESSES(accesses) {
			console.log("accesses:", accesses);
			this.accesses = accesses;
			uni.setStorageSync('accesses', accesses);
		},
		SET_ADDRESS(address) {
			this.address = address;
		},
		SET_ADDRESSES(addresses) {
			this.addresses = addresses;
		},
		SET_STORE(store) {
			this.store = store;
		},
		SET_CART(cart) {
			this.cart = cart;
		},
		REMOVE_CART(state) {
			this.cart = [];
		},
		setCookie(state, provider) {
			state.cookie = provider;
			uni.setStorage({
				key: "cookieKey",
				data: provider,
			});
		},
		SET_LOCATION(location) {
			if (location && location.latitude && location.longitude) {
				console.log('update location ', location)
				this.location = location;
			}
		},
		SET_OPENID(openid) {
			console.log('SET_OPENID called with:', openid);
			this.openid = openid;
			// 持久化存储 openid
			if (openid) {
				uni.setStorageSync('openid', openid);
				console.log('openid 已保存到本地存储:', openid);
			}
		},
		GET_OPENID() {
			// 如果内存中没有，从本地存储获取
			if (!this.openid) {
				const storedOpenid = uni.getStorageSync('openid');
				if (storedOpenid) {
					this.openid = storedOpenid;
					console.log('从本地存储恢复 openid:', storedOpenid);
				}
			}
			return this.openid;
		},
		CLEAR_OPENID() {
			this.openid = "";
			uni.removeStorageSync('openid');
			console.log('已清除 openid');
		},
		SET_TOKEN(token) {
			this.token = token;
			cookie.set("accessToken", token);
		},

		setAccessToken(user) {
			cookie.set("accessToken", user);
			// return getUserInfo()
		},
		setSelectAddress(id) {
			console.log("--> % setSelectAddress % id:\n", id);
			this.selectAddress = this.address.filter((item) => item.id == id)[0];
		},
		init() {
			let accessToken = cookie.get("accessToken");
			if (accessToken) {
				//return getUserInfo()
			}
			const storedOrderType = uni.getStorageSync("orderType");
			this.orderType = (storedOrderType && storedOrderType !== "") ? storedOrderType : "takein";
			console.log("load orderType", this.orderType);

			// 初始化时恢复 openid
			this.GET_OPENID();

			return null;
		},
		logout() {
			console.log('=== 开始执行退出登录 ===');

			// 清除store中的用户数据
			this.member = {};
			this.accesses = [];
			this.token = "";
			this.user = null;
			this.address = [];
			this.addresses = {};
			this.areaList = [];
			this.selectAddress = null;
			this.cart = [];
			this.mycoupon = {};
			this.buyerId = "";

			// 清除本地存储
			uni.removeStorageSync('userinfo');
			uni.removeStorageSync('accessToken');
			uni.removeStorageSync('accesses');
			uni.removeStorageSync('openid');
			uni.removeStorageSync('buyer_id');

			// 清除cookie
			cookie.remove('userinfo');
			cookie.remove('accessToken');

			// 登出时清除 openid
			this.CLEAR_OPENID();

			console.log('已清除所有用户数据');
			console.log('=== 退出登录完成 ===');

			// 跳转到登录页
			navigateTo("/pages/login/login");
		},
		restore() {
			// 恢复用户信息
			const userinfo = uni.getStorageSync('userinfo') || cookie.get('userinfo');
			const accessToken = uni.getStorageSync('accessToken') || cookie.get('accessToken');
			const accesses = uni.getStorageSync('accesses');
			console.log('[restore] userinfo:', userinfo);
			console.log('[restore] accessToken:', accessToken);
			console.log('[restore] accesses:', accesses);
			if (userinfo) {
				this.member = userinfo;
				console.log('[restore] 已恢复 member:', this.member);
			}
			if (accessToken) {
				this.token = accessToken;
				console.log('[restore] 已恢复 token:', this.token);
			}
			if (accesses) {
				this.accesses = accesses;
				console.log('[restore] 已恢复 accesses:', this.accesses);
			}

			// 恢复 openid
			this.GET_OPENID();
		},
		SET_BUYER_ID(buyerId) {
			this.buyerId = buyerId
		},
		CLEAR_USER_INFO() {
			this.openid = ''
			this.buyerId = ''
			this.member = null
			this.token = ''
			this.accesses = []
		}
	},
});